package com.chat.websocket.http;

import com.google.gson.Gson;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.DefaultFileRegion;
import io.netty.handler.codec.http.*;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedNioFile;
import io.netty.util.CharsetUtil;

import java.io.File;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @author 崔超
 * 2022/2/18
 */
public class HttpApi {

    static Map<String, BusinessFunc> routeMap = new HashMap<>();
    static List<Pattern> urlPatterns = new ArrayList<>();

    static {
        routeMap.put("/nickname/check", new CheckNickname());
        urlPatterns.add(Pattern.compile("/nickname/check/(.+)/(.+)"));
        routeMap.put("/all/persons", new GetAllPerson());
        urlPatterns.add(Pattern.compile("/all/persons/(.+)"));
    }

    public static String handleAPI(String url) {
        String[] result = checkUrl(url);
        if (result == null) {
            return new Gson().toJson(new Response(false, "404"));
        }

        String route = result[0];
        String[] params = new String[result.length - 1];
        System.arraycopy(result, 1, params, 0, result.length - 1);


        BusinessFunc businessFunc = routeMap.get(route);
        assert businessFunc != null;
        return businessFunc.go(params);
    }

    public static String[] checkUrl(String url) {
        for (Pattern pattern : urlPatterns) {
            Matcher matcher = pattern.matcher(url);
            if (!matcher.matches()) {
                continue;
            }
            int groupCount = matcher.groupCount();
            if (groupCount == 0) {
                return new String[]{url};
            }

            String[] back = new String[groupCount + 1];
            for (int i = 1; i <= groupCount; i++) {
                back[i] = matcher.group(i);
            }

            int firstParamIndex = url.indexOf(matcher.group(1)) - 1;
            back[0] = url.substring(0, firstParamIndex);
            return back;
        }
        return null;
    }
}
